package com.lenovo.smarttraffic.ui.activity.stage2;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lenovo.smarttraffic.Constant;
import com.lenovo.smarttraffic.MainActivity;
import com.lenovo.smarttraffic.R;
import com.lenovo.smarttraffic.ui.activity.BaseActivity;
import com.lenovo.smarttraffic.util.HttpUtils;
import com.lenovo.smarttraffic.util.ToastUtils;
import com.lenovo.smarttraffic.util.Utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

public class ChargeActivity extends BaseActivity {


    private Toolbar mToolbar;

    private Button findBtn;
    private TextView account_money_tv;

    private Spinner car_select, car_select_2;

    private EditText money_et;

    private Button charge_btn;

    private SharedPreferences preferences;

    private int money, threshold_min, threshold_max, chargeable, carId;

    private AlertDialog dialog;

    @Override
    protected int getLayout() {
        return R.layout.activity_account_charge;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        preferences = getSharedPreferences(Constant.ACCOUNT, MODE_PRIVATE);
        initView();
    }

    public void initView() {
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(view -> finish());


        findBtn = findViewById(R.id.findBtn);
        findBtn.setOnClickListener(view -> doFind());

        account_money_tv = findViewById(R.id.account_money);

        car_select = findViewById(R.id.car_select);
        car_select.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int pos, long id) {
                carId = pos + 1;
                doFind();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
//        car_select_2 = findViewById(R.id.car_select_2);

        money_et = findViewById(R.id.money_et);

        charge_btn = findViewById(R.id.charge_btn);
        charge_btn.setOnClickListener(view -> {
            String moneyStr = money_et.getText().toString();

            if (moneyStr.isEmpty()) {
                ToastUtils.showToast(this, "请输入账户余额", Toast.LENGTH_SHORT);
            } else if (Utils.parseInt(moneyStr) < 1) {
                ToastUtils.showToast(this, "充值金额不能小于1", Toast.LENGTH_SHORT);
            } else {
                if (dialog == null) {
                    dialog = new AlertDialog.Builder(this)
                            .setTitle("账户充值")
                            .setNegativeButton("取消", null)
                            .create();
                }

                dialog.setMessage(String.format(Locale.ENGLISH, "时间：%s\n账户余额：%d元\n车号：%d\n充值余额：%s元", SimpleDateFormat.getDateTimeInstance().format(new Date()), money, carId, moneyStr));

                dialog.setButton(AlertDialog.BUTTON_POSITIVE, "确定", (dialogInterface, i) -> {
                    int money_input = Utils.parseInt(moneyStr);

                    if (money > threshold_max || money < threshold_min) {
                        ToastUtils.showToast(ChargeActivity.this, "超出阈值，不允许充值", Toast.LENGTH_LONG);
                    } else if (money_input > chargeable) {
                        ToastUtils.showToast(ChargeActivity.this, String.format(Locale.ENGLISH, "充值失败，您本次最多只能充值%d元", chargeable), Toast.LENGTH_LONG);
                    } else {
                        HttpUtils.post(ChargeActivity.this, "set_car_account_recharge",
                                new HttpUtils().setParam("CarId", carId).
                                        setParam("Money", money_input).setParam("UserName", MainActivity.userName),
                                response1 -> {
                                    if (Utils.getResult(response1)) {
                                        Toast.makeText(ChargeActivity.this, "充值成功", Toast.LENGTH_SHORT).show();
                                        doFind();
                                    } else {
                                        Toast.makeText(ChargeActivity.this, "充值失败", Toast.LENGTH_SHORT).show();
                                    }
                                });
                    }
                });


                if (!dialog.isShowing()) {
                    dialog.show();

                    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(v -> {
                        if (!preferences.getBoolean(Constant.CHARGE_CANCEL_TIPS, false)) {
                            TextView textView = new TextView(this);
                            textView.setText("请问你真的要取消充值吗？可能会影响你的正常使用");
                            textView.setTextColor(getResources().getColor(R.color.Red));
                            textView.setPadding(70, 70, 70, 70);

                            new AlertDialog.Builder(ChargeActivity.this)
                                    .setTitle("提示")
                                    .setView(textView)
                                    .setPositiveButton("确定", (dialogInterface1, i1) -> dialog.dismiss())
                                    .setNegativeButton("取消", null)
                                    .setNeutralButton("不再提示", (dialogInterface12, i12) -> {
                                        dialog.dismiss();
                                        preferences.edit().putBoolean(Constant.CHARGE_CANCEL_TIPS, true).apply();
                                    }).show();
                        } else {
                            dialog.dismiss();
                        }
                    });
                }

                doFind();
            }
        });

        doFind();
    }

    private void doFind() {
        Map data = new Gson().fromJson(preferences.getString("car" + carId, null), Map.class);
        if (data != null) {
            threshold_min = Utils.parseInt((String) data.get(Constant.THRESHOLD_MIN));
            threshold_max = Utils.parseInt((String) data.get(Constant.THRESHOLD_MAX));
            chargeable = threshold_max - money;

            HttpUtils.post(this, "get_car_account_balance",
                    new HttpUtils().setParam("CarId", carId)
                            .setParam("UserName", MainActivity.userName),
                    response -> {
                        Map responseMap = new Gson().fromJson(response.toString(), Map.class);
                        if (responseMap.get("RESULT").equals("S")) {
                            money = (int) Utils.parseDouble(responseMap.get("Balance").toString());
                            account_money_tv.setText(String.format(Locale.ENGLISH, "账户余额：%d元", money));
                        } else {
                            Toast.makeText(this, "请求错误，可能没有这辆车", Toast.LENGTH_SHORT).show();
                        }
                    });
        } else {
            account_money_tv.setText("查询失败，请设置阈值");
        }

    }

}
